package com.li.configserve.utils.spring;

import com.li.toolkit.constant.LogConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description：
 * @Author：LiDong
 * @Create：2021/2/20
 * @Version：1.0.0
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {


    private static ApplicationContext applicationContext ;

    private static final Logger logger = LoggerFactory.getLogger(ApplicationContextUtils.class);

    @Override
    public void setApplicationContext( ApplicationContext  applicationContext) throws BeansException {
        if (Objects.isNull(ApplicationContextUtils.applicationContext)) {
            ApplicationContextUtils.applicationContext = applicationContext;
        }
        logger.info(LogConst.LOG_SUCCESS_PREFIX+"ApplicationContextUtils 注册完成！");
    }

    /**
     * 获得当前的ApplicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据名称拿到Bean
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 从ApplicationContext中获得Bean并且转型
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> tClass) {
        return getApplicationContext().getBean(tClass);
    }


}
